<?php
/**
 * 周舟 hzboye010@163.com
 * addby sublime snippets
 */
namespace Common\Api;
use Common\Api\Api;
use Common\Model\ScoreGoodsModel;
use Admin\Api\MemberApi;
use Common\Api\ExchangeLogApi;
use Admin\Api\AddressApi;
use Tool\Api\AreaApi;
use Tool\Api\CityApi;
use Tool\Api\ProvinceApi;

class ScoreGoodsApi extends Api{
  const QUERY    = "Common/ScoreGoods/myFind";
  const PAGE     = "Common/ScoreGoods/page";
  const ORPAGE   = "Common/ScoreGoods/query";
  const DELETE   = "Common/ScoreGoods/delete";
  const ADD      = "Common/ScoreGoods/add";
  const SAVE     = "Common/ScoreGoods/save";
  const DETAIL   = "Common/ScoreGoods/detail";
  const GET_INFO = "Common/ScoreGoods/getInfo";
  const CHANGE   = "Common/ScoreGoods/shelf";
  const GETPAYURL= "Common/ScoreGoods/getPayUrl";
  const EXCHANGE = "Common/ScoreGoods/exchange";

  public function myFind($start,$length,$order="create_time desc"){
    // $order = '';
    // return $this -> apiReturnSuc($order);
    $where = array('onshelf'=>1);//,'status'=>1
    $r     = $this-> model //->cache(true)
            // ->alias('g')
            // ->relation(true)
            // ->join(C('DB_PREFIX').'user_picture p ON g.main_img = p.id')
            // ->field('g.*,p.path')
            ->where($where)->limit($start,$length)->order($order)->select();
    // dump($r);
    // dump($this->getLastSql());exit;
    return $this -> apiReturnSuc($r);
  }

  public function shelf($gid,$onshelf){
    if($r = $this->model->where(array('id'=>$gid))->setField('onshelf',$onshelf))
      return $this->apiReturnSuc($r);//->cache(true)
    else
      return $this->apiReturnErr($r);
  }

  public function page($where,$page){
    // $where = array('game_id'=>$gid);
    $page = array('curpage'=>$page,'size'=>10);

    $r = $this -> model ->where($where);//->cache(true)

    $list = $r -> page($page['curpage'].','.$page['size']) -> select();
    if ($list === false) {
      $error = $this -> model -> getDbError();
      return $this -> apiReturnErr($error);
    }
    $count = $r -> count();
    $Page = new \Think\Page($count, $page['size']);
    //分页跳转的时候保证查询条件
    if ($params !== false) {
      foreach ($params as $key => $val) {
        $Page -> parameter[$key] = urlencode($val);
      }
    }
      $show = $Page -> show();
      return $this -> apiReturnSuc(array("show" => $show, "list" => $list));
  }

  public function exchange($uid,$psw,$pid){
        $msg = array();
        $msg['status'] = true;
        // $uid = $this->uid;
        $member = apiCall(MemberApi::GET_INFO,array(array('uid'=>$uid)));
        // dump($member);exit;
        if(!$member['status'])
        {
            $msg['info']= '非法用户';
            $msg['status'] = false;
            return $msg;
        }
        $mscore = intval($member['info']['score']);
        $sgoods = $this->getInfo(array('id'=>$pid));
        $score  = intval($sgoods['info']['score']);
        $price  = $sgoods['info']['price'];

        $exStatus = -1;
        // $this->assign('payurl',apiCall(ScoreGoodsApi::GETPAYURL,array($uid,$price)));
        // dump($member);
        // dump($sgoods);exit;
        if( $mscore < $score )
        {
           $msg['info']= '积分不足';
            $msg['status'] = false;
           return $msg;
        }
// $this->model-> startTrans();
        //减少积分
        $r = apiCall(MemberApi::SET_DEC,array(array('uid'=>$uid),'score',$score));
        if(!$r['status'])
        {
            $msg['info']= '系统错误： SCORE:DEC:ERROR';
            $msg['status'] = false;
            return $msg;
        }
        $member['info']['score'] = $mscore - $score;
        // $this->assign('user',$member['info']);
        // $msg['info']['user'] = $member['info'];
        // $this->assign('goods',$sgoods['info']);
        // $msg['info']['goods'] = $sgoods['info'];
        //查询发货地址
        $r = apiCall(AddressApi::QUERY_NO_PAGING,array(array('uid'=>$uid)));
        if(!$r['status'])
        {
            $msg['info']= '系统错误： Address ：get ERROR';
            $msg['status'] = false;
            return $msg;
        }
        // dump($r['info']);
        // $this->assign('address',$r['info']);
        $msg['info']['address'] =  $r['info'];
        //查询省份
        $r = apiCall(ProvinceApi::QUERY_NO_PAGING,array());
        if(!$r['status'])
        {
           $msg['info']= '系统错误： Province ：get ERROR';
            $msg['status'] = false;
           return $msg;
        }
        // $this->assign('topCats',$r['info']);
        // $msg['info']['topCats'] = $r['info'];
        $code = '';
        // if($price == 0) $exStatus = 0;
        // else{
          // $paycode =  $this->getPayUrl($uid,$price,'');
          // $code = $paycode['code'];
        // }
        //增加记录
        $map = array(
            'pid'              =>$pid
            ,'uid'             =>$uid
            ,'pname'           =>$sgoods['info']['name']
            ,'exchange_status' =>$exStatus
            ,'score'           =>$score
            ,'price'           =>$price
            // ,'pay_code'        =>$code
        );
        $r = apiCall(ExchangeLogApi::ADD,array($map));
        // dump($r);exit;
        if(!$r['status'] || !$r['info'])
        {
          $msg['info']= '系统错误：用户兑换:记录失败';
            $msg['status'] = false;
          return $msg;
        }
// if(!$msg['status']) $this-> model->rollback();
        $id = $r['info'];
        //地址选择页面
        // if($price>0)  
          $url = U('ExchangeLog/pay',array('uid'=>$uid,'psw'=>$psw,'id'=>$id));
        // else{
            // $url = U('ExchangeLog/index',array('uid'=>$uid,'psw'=>$psw));
        // }
            //,2,'<p style="font-size:20px;">支付成功，请耐心等待工作人员发货！页面将于2秒后跳转个人兑换记录</p>'
        if($id) $msg['info']   = $url;
        return $msg;
  }
	//初始化
  protected function _init(){
  	$this -> model  = new ScoreGoodsModel();
  }

  public function detail($id){
    $entry = $this-> model->find($id);// ->cache(true)
    // dump($entry);exit;
    return $entry;
  }
  public function getPayUrl($uid,$price,$psw){
    $now  = time();
    $code = 'S'.$now.'U'.$uid;
    $name = '订单'.$code;
    $desc = $name;
    //保留2位
    $total_price = round($price,2);
    $info = array(
        'code'=>$code,
        'name'=>$name,
        'desc'=>$desc,
        //@author 老胖子-何必都 <hebiduhebi@126.com>
        //转换成字符串，否则IOS端解析成数字类型时精度会有问题，比如74.10 被解析成74.09999999999999,从而导致APP端验证失败!
        'total_price'=>strval($total_price)
    );

    $encode = urlencode($code.$name.$desc.$total_price);
    $encode = md5(strtolower($encode));

    $info['key'] = pay_encrypt_md5($encode);
    $info['show_url'] = '';//U('Webview/ExchangeLog/payBack',array('uid'=>$uid,'psw'=>$psw));
    return array('url'=>'com.itboye.sunsun-china
://?type=SUNSUN_ALIPAY_FOR_SCOREGOODS&code='.$info['code'].'&name='.$info['name'].'&desc='.$info['desc'].'&total_price='.$info['total_price'].'&key='.$info['key'].'&show_url='.$info['show_url'],'code'=>$info['code']);
    // return array('url'=>'com.itboye.sunsunchina://?type=SUNSUN_ALIPAY_FOR_SCOREGOODS&code='.$info['code'].'&name='.$info['name'].'&desc='.$info['desc'].'&total_price='.$info['total_price'].'&key='.$info['key'].'&show_url='.$info['show_url'],'code'=>$info['code']);

    }
}